#!/usr/bin/python

import codecs, sys
from xml.dom.minidom import parse
try:
	from urllib.parse import quote, unquote, urlencode
	from urllib.request import Request, urlopen
except ImportError:
	from urllib import quote, unquote, urlencode
	from urllib2 import Request, urlopen

########## PERSONALIZE THIS ##########
email = 'example@gmail.com'
password = 'secret'
######################################

if sys.version < '3':
	UTF8Writer = codecs.getwriter('utf8')
	sys.stdout = UTF8Writer(sys.stdout)

if len(sys.argv) < 2:
	sys.exit("Usage: %s feed-URL" % sys.argv[0])
feedUrl = sys.argv[1]
feedUrl = unquote(feedUrl) # in case already quoted
feedUrl = quote(feedUrl)

clientapp, service = 'reader', 'reader'
params = urlencode({'Email': email, 'Passwd': password, 'source': clientapp, 'service': service}).encode('ascii')
req = Request(url='https://www.google.com/accounts/ClientLogin', data=params)
f = urlopen(req)

for line in f.readlines():
	line = line.decode('ascii')
	if line[0:5] == 'Auth=':
		auth=line[5:]

root = "http://www.google.com/reader/api/0/"
req = Request(root + "token") 	# Apparently we need to request a token, but we don't actually need to use it
req.add_header('Authorization', 'GoogleLogin auth=' + auth)
f = urlopen(req)

continuation = None
firstGet = True 

print('<feed xmlns:media="http://search.yahoo.com/mrss/" xmlns:gr="http://www.google.com/schemas/reader/atom/" xmlns:idx="urn:atom-extension:indexing" xmlns="http://www.w3.org/2005/Atom" idx:index="no" gr:dir="ltr">')

while firstGet == True or continuation != None:
	url = "http://www.google.com/reader/atom/feed/" + feedUrl + "?n=1000"
	if continuation != None:
		url = url + "&c=" + continuation
		doc.unlink()
		f.close()
	req = Request(url)
	req.add_header('Authorization', 'GoogleLogin auth=' + auth)
	f = urlopen(req)
	doc = parse(f)
	topnode = doc.documentElement
	continuation = None
	
	for feedElement in topnode.childNodes:
		if feedElement.localName == "entry":
			categoryElements = feedElement.getElementsByTagName("category")
			for c in categoryElements:
				if c.getAttributeNode("term").value[0:4] == "user":
					feedElement.removeChild(c)	# Strip category tag with user Google user ID
			print(feedElement.toxml())
		elif feedElement.localName == "continuation":
			continuation = feedElement.firstChild.data
		elif firstGet == True:	# only print feed property elements once
			print(feedElement.toxml())

	firstGet = False

print('</feed>')
